package com.mingqijia.gassafety.job.job.warnStrategy;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gap.cache.redis.RedisCache;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.mingqijia.gassafety.db.entity.*;
import com.mingqijia.gassafety.db.entity.vo.SendMessagePhonesVo;
import com.mingqijia.gassafety.db.mapper.*;
import com.mingqijia.gassafety.job.dto.SendMessageDTO;
import com.mingqijia.gassafety.job.response.VccUserRseponse;
import com.mingqijia.gassafety.job.service.ConsumerService;
import com.mingqijia.gassafety.job.service.RunningReportDataService;
import com.mingqijia.gassafety.job.service.impl.CompanyServiceImpl;
import com.mingqijia.gassafety.job.strategy.MessageContext;
import com.mingqijia.gassafety.job.strategy.RecordService;
import com.mingqijia.gassafety.shared.constant.*;
import com.mingqijia.gassafety.shared.dto.AssembleTemplateDTO;
import com.mingqijia.gassafety.shared.utils.RedisCacheExt;
import com.mingqijia.gassafety.shared.utils.commonUtils.DateUtils;
import com.mingqijia.gassafety.shared.utils.commonUtils.SnowflakeUtil;
import com.mingqijia.gassafety.shared.utils.message.SendMessageService;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author mby
 * @version 1.0.0
 * @ClassName RunningReportJob.java
 * @Description TODO
 * @createTime 2024年03月11日
 */
@Component
@Slf4j
public class RunningReportStrategyInstantlyJob {

    @Autowired
    RedisCacheExt redisUtil;
    @Autowired
    RedisCache redisCache;
    @Autowired
    MessageContext messageContext;

    @Autowired
    ConsumerMapper consumerMapper;
    @Autowired
    RunningStrategyMapper runningStrategyMapper;
    @Autowired
    RunningStrategyExtMapper extMapper;
    @Autowired
    ContactsMapper contactsMapper;
    @Autowired
    BusinessNoticeMapper noticeMapper;
    @Autowired
    JvInfoMapper jvInfoMapper;
    @Autowired
    RunningReportConfigMapper runningReportConfigMapper;
    @Autowired
    RunningReportMapper runningReportMapper;
    @Autowired
    RunningReportDataMapper runningReportDataMapper;
    @Autowired
    HistoryAlarmMapper historyAlarmMapper;
    @Autowired
    HistoryBrokenMapper historyBrokenMapper;

    @Autowired
    RunningReportDataService runningReportDataService;
    @Autowired
    RecordService runningRecordService;
    @Autowired
    CompanyServiceImpl companyService;
    @Autowired
    ConsumerService consumerService;

    public static final Integer pageSize = 1000;
    @Autowired
    private SendMessageService sendMessageService;

    /**
     *   十分钟一次 设备运行报告推送即刻  0 0/10 * * * *
     */
    @XxlJob("runningReportStrategyInstantlyJob")
    public ReturnT<String> runningReportStrategyInstantlyJob(String param) {
        XxlJobLogger.log("XXLJOB-runningReportStrategyInstantlyJob start..." );
        log.info("runningReportStrategyInstantlyJob--start--------");
        String key = Constants.EQUIPMENT_RUNNING_INSTANTLY_REPORT_STRATEGY;
        try {
            Boolean acquire = redisUtil.setIfAbsent(key, String.valueOf(System.currentTimeMillis()), Constants.TIME_OUT_TWO_HOUR);//2小时超时
            if (acquire) {
                try {
                    execute();
                    return ReturnT.SUCCESS;
                } catch (Exception e) {
                    log.error("runningReportStrategyInstantlyJob-error:{}", e);
                } finally {
                    redisUtil.del(key);
                }
            }
        } catch (Exception e) {
            log.error("runningReportStrategyInstantlyJob-error:{}", e);
        }
        log.info("runningReportStrategyInstantlyJob--end--------");
        XxlJobLogger.log("XXLJOB-runningReportStrategyInstantlyJob end..." );
        return ReturnT.SUCCESS;
    }

    private boolean execute() {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, -1);
        String reportDate = DateUtils.dateFormat(c.getTime(), "yyyy-MM");
        log.info("runningReportStrategyInstantlyJob-月份:{}", reportDate);
        String yearMonth = new StringBuilder().append(c.get(Calendar.YEAR)).append("年").append(c.get(Calendar.MONTH) + 1).append("月").toString();

        // 客户ID，保证从具体客户-行业选择-所有客户的优先级，避免客户策略重复
        // 用于存放已经匹配策略的客户id，key为spID,value为该spId下的所有客户id
        Map<String, List<Integer>> consumerMapBySpId = new HashMap<>();
        // 用于存放已经匹配策略的客户id，key为spID,value为该spId下的行业编码
        Map<String, List<String>> industryTypeMapBySpId = new HashMap<>();

        //所有有效的设备运行报告策略
        QueryWrapper<RunningStrategy> strategyQueryWrapper = new QueryWrapper<>();
        strategyQueryWrapper.lambda().eq(RunningStrategy::getIsDeleted,0)
            .eq(RunningStrategy::getIsDisabled,0)
            .eq(RunningStrategy::getStrategyType,2)
            .orderByDesc(RunningStrategy::getStrategyObj); //根据策略对象类型降序
        List<RunningStrategy> strategyList = runningStrategyMapper.selectList(strategyQueryWrapper);
        if (CollectionUtils.isNotEmpty(strategyList)) {
            for (RunningStrategy strategy : strategyList) {
                if (consumerMapBySpId.get(strategy.getSpId()) == null) {
                    consumerMapBySpId.put(strategy.getSpId(), new ArrayList<>());
                }
                if (industryTypeMapBySpId.get(strategy.getSpId()) == null) {
                    industryTypeMapBySpId.put(strategy.getSpId(), new ArrayList<>());
                }
                // 查询对应的策略明细
                //对应客户详细的策略信息
                QueryWrapper<RunningStrategyExt> extQueryWrapper = new QueryWrapper<>();
                extQueryWrapper.lambda().eq(RunningStrategyExt::getIsDeleted,0)
                        .in(RunningStrategyExt::getStrategyId,strategy.getId());
                List<RunningStrategyExt> runningStrategyExts = extMapper.selectList(extQueryWrapper);
                Map<Integer, RunningStrategyExt> strategyMap = new HashMap<>();
                if (CollectionUtils.isEmpty(runningStrategyExts)) {
                    log.info("runningReportStrategyInstantlyJob-策略明细为空：strategyId：{}", strategy.getId());
                    continue ;
                } else if (runningStrategyExts.get(0).getPushTime() != DtuPushTypeEnum.PUSH_0.getCode()) {
                    log.info("runningReportStrategyInstantlyJob-不是即刻报警：strategyId：{}", strategy.getId());
                    continue ;
                } else {
                    runningStrategyExts.stream().forEach(x -> {
                        strategyMap.put(x.getPushType(), x);
                    });
                    log.info("runningReportStrategyInstantlyJob-策略明细：strategy：{},strategyMap：{}", strategy.toString(), strategyMap);
                }
                // 公司信息
                // 公司电话
                QueryWrapper<BusinessNotice> query = new QueryWrapper<>();
                query.lambda().or().eq(BusinessNotice::getIsDeleted, 0)
                        .eq(BusinessNotice::getSpId, strategy.getSpId())
                        .eq(BusinessNotice::getParamCode, BusinessNoticeParam.CM_SERVICE_HOT_LINE.getCode());
                List<BusinessNotice> r = noticeMapper.selectList(query);
                String phone = "";
                if (!CollectionUtil.isEmpty(r)) phone = r.get(0).getParamValue();

                String orgName = "";
                QueryWrapper<JvInfo> jvInfoQuery = new QueryWrapper<>();
                jvInfoQuery.lambda().or().eq(JvInfo::getIsDeleted, 0)
                        .eq(JvInfo::getSpId, strategy.getSpId());
                List<JvInfo> jvInfo = jvInfoMapper.selectList(jvInfoQuery);
                if (!CollectionUtil.isEmpty(jvInfo)) orgName = jvInfo.get(0).getName();
                log.info("runningServicePeriodStrategy-strategyId：{},spId：{},orgName:{},phone：{}", strategy.getId(),
                        strategy.getSpId(), orgName, phone);
                int pageIndex = 1;
                long total = 0;
                // 查询客户,正常报警策略
                QueryWrapper<RunningReport> runningReportQueryWrapper = new QueryWrapper<>();
                runningReportQueryWrapper.lambda().eq(RunningReport::getIsDeleted,0)
                    .eq(RunningReport::getSpId,strategy.getSpId())
                    .eq(RunningReport::getReportDate,reportDate)
                    .eq(RunningReport::getIsSend,0)
                    .in(RunningReport::getCheckStatus,Arrays.asList(1,2));
                if (strategy.getStrategyObj() == 3) {
                    //按服务套餐
                    QueryWrapper<Consumer> comsumerQueryWrapper = new QueryWrapper<>();
                    String[] pkgIdArr = strategy.getStrategyObjValues().split(";");
                    comsumerQueryWrapper.lambda().in(Consumer::getPkgId, pkgIdArr)
                            .eq(Consumer::getIsDeleted,0)
                            .eq(Consumer::getSpId,strategy.getSpId());
                    List<Consumer> pkgConsumerList = consumerMapper.selectList(comsumerQueryWrapper);
                    if (CollectionUtils.isNotEmpty(pkgConsumerList)) {
                        List<Integer> nowConsumerIds = pkgConsumerList.stream().map(Consumer::getId).collect(Collectors.toList());
                        consumerMapBySpId.get(strategy.getSpId()).addAll(nowConsumerIds);
                        runningReportQueryWrapper.lambda().in(RunningReport::getConsumerId,nowConsumerIds);
                    }
                } else if (strategy.getStrategyObj() == 2) {
                    //按客户
                    List<Integer> nowConsumerIds = Arrays.stream(strategy.getStrategyObjValues().split(";"))
                        .filter(str -> !str.isEmpty()).map(str -> Integer.parseInt(str)).collect(Collectors.toList());
                    consumerMapBySpId.get(strategy.getSpId()).addAll(nowConsumerIds);
                    runningReportQueryWrapper.lambda().in(RunningReport::getConsumerId,nowConsumerIds);
                } else if (strategy.getStrategyObj() == 1) {
                    //按行业
                    List<String> industryTypeList = Arrays.stream(strategy.getStrategyObjValues().split(";"))
                        .filter(str -> !str.isEmpty()).collect(Collectors.toList());
                    industryTypeMapBySpId.get(strategy.getSpId()).addAll(industryTypeList);
                    runningReportQueryWrapper.lambda().in(RunningReport::getIndustryType,industryTypeList);
                } else if (strategy.getStrategyObj() != 0) {
                    runningReportQueryWrapper.lambda().notIn(CollectionUtils.isNotEmpty(consumerMapBySpId.get(strategy.getSpId())),
                        RunningReport::getConsumerId, consumerMapBySpId.get(strategy.getSpId()))
                        .notIn(CollectionUtils.isNotEmpty(industryTypeMapBySpId.get(strategy.getSpId())),
                        RunningReport::getIndustryType, industryTypeMapBySpId.get(strategy.getSpId()));
                }
                do {
                    Page<RunningReport> pages = PageHelper.startPage(pageIndex, pageSize);
                    List<RunningReport> runningReportList = runningReportMapper.selectList(runningReportQueryWrapper);
                    pageIndex++;
                    total = pages.getTotal();
                    log.info("runningReportStrategyInstantlyJob-strategyId：:{},runningReportList-total:{}", strategy.getId(), total);
                    // 可以发送的数据列表
                    List<SendMessageDTO> data = new ArrayList<>();
                    if (CollectionUtils.isNotEmpty(runningReportList)) {
                        for (RunningReport runningReport : runningReportList) {
                            Long snowflakeId = SnowflakeUtil.getSnowflakeId();
                            try {
                                if (strategy.getAdviceType().contains(String.valueOf(MessagePushTypeEnum.SMS.getCode()))) {
                                    RunningStrategyExt ext = strategyMap.get(MessagePushTypeEnum.SMS.getCode());
                                    createData(MessagePushTypeEnum.SMS, runningReport, ext, data, orgName, phone, snowflakeId, yearMonth, strategy);
                                }
                            } catch (Exception e) {
                                log.error("runningReportStrategyInstantlyJob-sms-error:{}", e);
                            }
                            try {
                                if (strategy.getAdviceType().contains(String.valueOf(MessagePushTypeEnum.WX.getCode()))) {
                                    RunningStrategyExt ext = strategyMap.get(MessagePushTypeEnum.WX.getCode());
                                    createData(MessagePushTypeEnum.WX, runningReport , ext, data, orgName, phone, snowflakeId, yearMonth, strategy);
                                }
                            } catch (Exception e) {
                                log.error("runningReportStrategyInstantlyJob-wx-error:{}", e);
                            }
                            try {
                                if (strategy.getAdviceType().contains(String.valueOf(MessagePushTypeEnum.CALL.getCode()))) {
                                    RunningStrategyExt ext = strategyMap.get(MessagePushTypeEnum.CALL.getCode());
                                    createData(MessagePushTypeEnum.CALL, runningReport, ext, data, orgName, phone, snowflakeId, yearMonth, strategy);
                                }
                            } catch (Exception e) {
                                log.error("runningReportStrategyInstantlyJob-call-error:{}", e);
                            }
                            // 更新 is_send
                            runningReport.setIsSend(1);
                            runningReportMapper.updateById(runningReport);

                        }
                    }
                    log.info("runningReportStrategyInstantlyJob-strategyId：:{},sendDataList:{}", strategy.getId(), data);
                    if (CollectionUtils.isNotEmpty(data)) {
                        messageContext.getMessageStrategy("sendSmsMessageStrategy").sendMessage(data, "runningReportStrategyInstantlyJob", runningRecordService);
                        messageContext.getMessageStrategy("sendWxMessageStrategy").sendMessage(data, "runningReportStrategyInstantlyJob", runningRecordService);
                        messageContext.getMessageStrategy("sendCallMessageStrategy").sendMessage(data, "runningReportStrategyInstantlyJob", runningRecordService);
                    }
                }while(total > (pageIndex - 1) * pageSize);

                // c端预览发送
                int previewPageIndex = 1;
                long previewTotal = 0;
                // 查询客户,正常报警策略
                QueryWrapper<RunningReport> previewRunningReportQueryWrapper = new QueryWrapper<>();
                previewRunningReportQueryWrapper.lambda().eq(RunningReport::getIsDeleted,0)
                        .eq(RunningReport::getSpId,strategy.getSpId())
                        .eq(RunningReport::getIsAdvanceSend,0)
                        .eq(RunningReport::getCheckStatus,0)
                        .ne(RunningReport::getPhone,Constants.BLANK);
                if (strategy.getStrategyObj() == 2) {
                    //按客户
                    List<Integer> nowConsumerIds = Arrays.stream(strategy.getStrategyObjValues().split(";"))
                            .filter(str -> !str.isEmpty()).map(str -> Integer.parseInt(str)).collect(Collectors.toList());
                    consumerMapBySpId.get(strategy.getSpId()).addAll(nowConsumerIds);
                    previewRunningReportQueryWrapper.lambda().in(RunningReport::getConsumerId,nowConsumerIds);
                } else if (strategy.getStrategyObj() == 1) {
                    //按行业
                    List<String> industryTypeList = Arrays.stream(strategy.getStrategyObjValues().split(";"))
                            .filter(str -> !str.isEmpty()).collect(Collectors.toList());
                    industryTypeMapBySpId.get(strategy.getSpId()).addAll(industryTypeList);
                    previewRunningReportQueryWrapper.lambda().in(RunningReport::getIndustryType,industryTypeList);
                } else if (strategy.getStrategyObj() != 0) {
                    previewRunningReportQueryWrapper.lambda().notIn(CollectionUtils.isNotEmpty(consumerMapBySpId.get(strategy.getSpId())),
                        RunningReport::getConsumerId, consumerMapBySpId.get(strategy.getSpId()))
                        .notIn(CollectionUtils.isNotEmpty(industryTypeMapBySpId.get(strategy.getSpId())),
                        RunningReport::getIndustryType, industryTypeMapBySpId.get(strategy.getSpId()));
                }
                do {
                    Page<RunningReport> previewPages = PageHelper.startPage(previewPageIndex, pageSize);
                    List<RunningReport> previewRunningReportList = runningReportMapper.selectList(previewRunningReportQueryWrapper);
                    previewPageIndex++;
                    previewTotal = previewPages.getTotal();
                    log.info("runningReportStrategyInstantlyJob-strategyId：:{},previewRunningReportList-total:{},list:{}", strategy.getId(), previewTotal, previewRunningReportList);
                    // 可以发送的数据列表
                    List<SendMessageDTO> data = new ArrayList<>();
                    if (CollectionUtils.isNotEmpty(previewRunningReportList)) {
                        for (RunningReport runningReport : previewRunningReportList) {
                            // 预览的可能不是上个月的
                            String previewYearMonth = yearMonth;
                            if (!runningReport.getReportDate().equals(reportDate)) {
                                Date previewDate = DateUtils.toDate(runningReport.getReportDate(), "yyyy-MM");
                                Calendar previewCalendar = Calendar.getInstance();
                                previewCalendar.setTime(previewDate);
                                previewYearMonth = new StringBuilder().append(previewCalendar.get(Calendar.YEAR)).append("年").append(previewCalendar.get(Calendar.MONTH) + 1).append("月").toString();
                            }
                            Long snowflakeId = SnowflakeUtil.getSnowflakeId();
                            try {
                                if (strategy.getAdviceType().contains(String.valueOf(MessagePushTypeEnum.SMS.getCode()))) {
                                    RunningStrategyExt ext = strategyMap.get(MessagePushTypeEnum.SMS.getCode());
                                    createData(MessagePushTypeEnum.SMS, runningReport, ext, data, orgName, phone, snowflakeId, previewYearMonth, strategy);
                                }
                            } catch (Exception e) {
                                log.error("runningReportStrategyInstantlyJob-sms-error:{}", e);
                            }
                            try {
                                if (strategy.getAdviceType().contains(String.valueOf(MessagePushTypeEnum.WX.getCode()))) {
                                    RunningStrategyExt ext = strategyMap.get(MessagePushTypeEnum.WX.getCode());
                                    createData(MessagePushTypeEnum.WX, runningReport , ext, data, orgName, phone, snowflakeId, previewYearMonth, strategy);
                                }
                            } catch (Exception e) {
                                log.error("runningReportStrategyInstantlyJob-wx-error:{}", e);
                            }
                            try {
                                if (strategy.getAdviceType().contains(String.valueOf(MessagePushTypeEnum.CALL.getCode()))) {
                                    RunningStrategyExt ext = strategyMap.get(MessagePushTypeEnum.CALL.getCode());
                                    createData(MessagePushTypeEnum.CALL, runningReport, ext, data, orgName, phone, snowflakeId, previewYearMonth, strategy);
                                }
                            } catch (Exception e) {
                                log.error("runningReportStrategyInstantlyJob-call-error:{}", e);
                            }
                            // 更新 is_send
                            runningReport.setIsAdvanceSend(1);
                            runningReportMapper.updateById(runningReport);

                        }
                    }
                    log.info("runningReportStrategyInstantlyJob-strategyId：:{},previewSendDataList:{}", strategy.getId(), data);
                    if (CollectionUtils.isNotEmpty(data)) {
                        messageContext.getMessageStrategy("sendSmsMessageStrategy").sendMessage(data, "runningReportStrategyInstantlyJob", runningRecordService);
                        messageContext.getMessageStrategy("sendWxMessageStrategy").sendMessage(data, "runningReportStrategyInstantlyJob", runningRecordService);
                        messageContext.getMessageStrategy("sendCallMessageStrategy").sendMessage(data, "runningReportStrategyInstantlyJob", runningRecordService);
                    }
                }while(previewTotal > (previewPageIndex - 1) * pageSize);
            }
        }
        consumerMapBySpId.clear();
        industryTypeMapBySpId.clear();

        return true;
    }


    /**
     * 组装数据
     * @param pushType 推送方式
     * @param report 运行报告
     * @param ext  策略信息
     * @param data 组装的发送数据
     * @param orgName 公司名称
     * @param orgPhone 公司电话
     * @param snowflakeId uuid
     * @param yearMonth 年月
     */
    public void createData(MessagePushTypeEnum pushType, RunningReport report,
                                       RunningStrategyExt ext, List<SendMessageDTO> data, String orgName, String orgPhone,
                                       Long snowflakeId, String yearMonth, RunningStrategy strategy) {
        if (ext == null) {
            log.info("runningReportStrategyInstantlyJob-查找不到对应策略：consumerId：{}，reportDate：{}，pushType：{}",
                    report.getConsumerId(), report.getReportDate(), pushType.getCode());
            return ;
        }

        String orgCode = companyService.getOrgCode(report.getSpId(), String.valueOf(report.getConsumerId()));
        QueryWrapper<Consumer> consumerQuery = new QueryWrapper<>();
        consumerQuery.lambda().eq(Consumer::getIsDeleted, 0)
                .eq(Consumer::getSpId, report.getSpId())
                .eq(Consumer::getId, report.getConsumerId());
        Consumer consumer = consumerService.getOne(consumerQuery);

        SendMessageDTO dto = new SendMessageDTO();
        dto.setStrategyType(StrategyTypeEnum.DEVICE_RUNNING.getCode());
        List<SendMessagePhonesVo> phones = new ArrayList<>();

        // C端预览电话
        if (report.getCheckStatus() == 0) {
            // 待审核说明是根据C端预览来的
            dto.setSendType(1);
            SendMessagePhonesVo previewPhone = new SendMessagePhonesVo();
            previewPhone.setTelephone(report.getPhone());
            previewPhone.setLevel("0");
            previewPhone.setNotifyObjType(0);
            phones.add(previewPhone);
        } else {
            if (pushType == MessagePushTypeEnum.SMS || pushType == MessagePushTypeEnum.CALL) {
                if (org.apache.commons.lang3.StringUtils.isNotEmpty(ext.getPushLevel()) && !"0".equals(ext.getPushLevel())){
                    List<SendMessagePhonesVo> contractPhoneList= contactsMapper.selectServicePeriodPhones(report.getConsumerId(), Arrays.asList(ext.getPushLevel().split(";")));
                    if (CollectionUtils.isNotEmpty(contractPhoneList)) {
                        phones.addAll(contractPhoneList);
                    }
                }
            } else if (pushType == MessagePushTypeEnum.WX && org.apache.commons.lang.StringUtils.isNotEmpty(dto.getSubsCode())
                    && org.apache.commons.lang.StringUtils.isNotEmpty(dto.getOrgCode())) {
                log.info("runningReportStrategyInstantlyJob-getVccUser：subsCode：{},orgCode：{}", dto.getSubsCode(),dto.getOrgCode());
                VccUserRseponse vccUser = consumerService.getVccUser(dto.getSubsCode(), "", dto.getOrgCode());
                if (vccUser ==null ){
                    log.info("runningReportStrategyInstantlyJob-getVccUser：vcc不存在");
                } else {
                    log.info("runningReportStrategyInstantlyJob-getVccUser：{}", vccUser);
                    dto.setPhone(vccUser.getCustPhone());
                    dto.setLevel(ext.getPushLevel());
                }
            }
        }
        dto.setVerb(yearMonth);
        dto.setConsumerId(report.getConsumerId());
        dto.setSpId(report.getSpId());
        dto.setStrategyId(ext.getStrategyId());
        dto.setPushType(pushType.getCode());
        dto.setPushTypeCode(pushType.getValue());
        dto.setStrategyId(ext.getStrategyId());
        dto.setPhones(phones);
        dto.setOrgCode(orgCode);
        dto.setOrgName(orgName);
        dto.setExt(ext);
        dto.setSnowflakeId(snowflakeId);
        Map<String, Object> param = new HashMap<>();
        dto.setParam(param);
        if (report.getCheckStatus() == 0) {
            param.put("imei", report.getImei());
            param.put("isForTrial", 1);
            Calendar c = Calendar.getInstance();
            c.add(Calendar.HOUR_OF_DAY, 2);
            param.put("timeStamp", c.getTime().getTime());
        } else {
            param.put("imei", Constants.BLANK);
            param.put("isForTrial", Constants.BLANK);
            param.put("timeStamp", Constants.BLANK);
        }
        param.put("reportDate", report.getReportDate());
        param.put("Date", yearMonth);
        param.put("phone", orgPhone);
        param.put("position", Constants.BLANK);
        param.put("address", Constants.BLANK);
        param.put("subsName", Constants.BLANK);
        param.put("subsCode", Constants.BLANK);
        dto.setOrgPhone(orgPhone);
        if (consumer != null) {
            dto.setAddress(consumer.getCustAddress());
            dto.setCustName(consumer.getCustName());
            dto.setSubsCode(consumer.getSubsCode());
            dto.setName(consumer.getName());
            param.put("address", consumer.getCustAddress() == null ? Constants.BLANK : consumer.getCustAddress());
            param.put("subsName", consumer.getCustName() == null ? Constants.BLANK : consumer.getCustName());
            param.put("subsCode", consumer.getSubsCode() == null ? Constants.BLANK : consumer.getSubsCode());
            param.put("CustomerName", consumer.getName() == null ? Constants.BLANK : consumer.getName());
        }
        if (pushType == MessagePushTypeEnum.WX && param.get("address").toString().length() > 20) {
            param.put("address", param.get("address").toString().substring(0, 20)); // 联系人地址
        }
        if (pushType == MessagePushTypeEnum.WX &&
            param.get("subsName").toString().length() > 18 - param.get("subsCode").toString().length()) {
            param.put("subsName", param.get("subsName").toString().substring(0, 15 - param.get("subsCode").toString().length()) + "..."); // 联系人地址
        }
        dto.setParam(param);
        AssembleTemplateDTO assembleTemplate = new AssembleTemplateDTO();
        assembleTemplate.setSpId(report.getSpId());
        assembleTemplate.setOrgCode(orgCode);
        if (pushType == MessagePushTypeEnum.SMS) {
            dto.setSendCode(Constants.RUNNING_STRATEGY_REPORT);
            if (StringUtils.isNotEmpty(strategy.getSmsMsgCode())) {
                assembleTemplate.setSmsMsgCode(strategy.getSmsMsgCode());
                dto.setSendCode(strategy.getSmsMsgCode());
            }
            String content = sendMessageService.getSmsContent(dto.getSendCode(), param, assembleTemplate);
            dto.setContent(content);
            //dto.setContent(getSmsTemplate(dto, orgPhone));
        } else  if (pushType == MessagePushTypeEnum.WX) {
            dto.setSendCode(Constants.RUNNING__WX_STRATEGY_REPORT);
            if (StringUtils.isNotEmpty(strategy.getWxMsgCode())) {
                assembleTemplate.setWxMsgCode(strategy.getWxMsgCode());
                dto.setSendCode(strategy.getWxMsgCode());
            }
            String content = sendMessageService.getWxContent(dto.getSendCode(), param, assembleTemplate);
            dto.setContent(content);
            //dto.setContent(getWxTemplate(dto));
        } else  if (pushType == MessagePushTypeEnum.CALL) {
            dto.setContent(getCallTemplate(dto, Constants.WARNING_CALL_MESSAGES_REPORT, orgPhone));
        }
        data.add(dto);
    }

    /**
     * 自定义话术格式化
     * @param dto
     * @param robotContent
     * @param phone
     * @return
     */
    public String getCallTemplate(SendMessageDTO dto, String robotContent, String phone) {
        return robotContent.replace("#name#", dto.getOrgName() == null ? "" : dto.getOrgName())
                .replace("#address#", dto.getAddress() == null ? "" : dto.getAddress())
                .replace("#date#", dto.getVerb() == null ? "" : dto.getVerb());
    }



}